package hu.uniobuda.nik.bsik2f.FileBrowser;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;

/**
 * Created with IntelliJ IDEA.
 * User: Matusinka Roland
 * Date: 2013.03.16.
 * Time: 16:17
 */

class FileListAdapter extends ArrayAdapter<File> {

    private final int layoutResourceId;
    private final Context context;
    private File[] data = null;

    public FileListAdapter(Context context, int layoutResourceId, File[] data, int SORT_MODE) {
        super(context, layoutResourceId, data);
        this.context = context;
        this.layoutResourceId = layoutResourceId;
        if (data.length > 0) switch (SORT_MODE) {
            default:
            case BrowserActivity.SORT_BY_NAME:
                this.data = Utils.sortByName(data);
                break;
        }
        else this.data = new File[]{new File(this.context.getResources().getString(R.string.empty_folder))};
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        FileHolder holder;

        if (row == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);

            holder = new FileHolder();
            holder.icon = (ImageView) row.findViewById(R.id.listItemIcon);
            holder.text = (TextView) row.findViewById(R.id.listItemText);


            row.setTag(holder);
        } else {
            holder = (FileHolder) row.getTag();
        }

        holder.file = data[position];
//        SpannableStringBuilder ssb = new SpannableStringBuilder(" " + holder.browser_file.getName());
//        Bitmap icon = null;

        if (holder.file.isDirectory()) {
            holder.icon.setImageDrawable(context.getResources().getDrawable(R.drawable.browser_folder_closed));
            //icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.browser_folder_closed);
        }
        if (holder.file.isFile()) {
            holder.icon.setImageDrawable(context.getResources().getDrawable(R.drawable.browser_file));
            //icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.browser_file);
        }

        //ssb.setSpan(new ImageSpan(icon), 0, 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        //holder.text.setText(ssb, TextView.BufferType.SPANNABLE);
        holder.text.setText(holder.file.getName());
        return row;
    }

}

class FileHolder {
    ImageView icon;
    TextView text;
    File file;
}